package com.windy.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.windy.util.TransportObject;

public class BaseDAO<T> extends HibernateDaoSupport {

	private Class<T> entityClass;
	
	@SuppressWarnings("unchecked")
	public BaseDAO() {
		entityClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public void saveOrUpdate(T domain) {
		getHibernateTemplate().saveOrUpdate(domain);
	}

	public void remove(T domain) {
		getHibernateTemplate().delete(domain);
	}
	
	@SuppressWarnings("unchecked")
	public T get(Serializable id) {
		T o = (T) getHibernateTemplate().get(entityClass, id);
		return o;
	}
	
	@SuppressWarnings("unchecked")
	public TransportObject findList(Criteria criteria, String orderField, int start, int size)
	{
		TransportObject to = new TransportObject();
		
		to.setTotalRecords(Integer.parseInt(criteria.setProjection(Projections.countDistinct("id")).uniqueResult().toString()));
		criteria.setProjection(null);
		
		if(orderField != null )
		{
			criteria.addOrder(Order.desc(orderField));
		}
		criteria.setFirstResult(start);
		criteria.setMaxResults(size);
		
		to.setResultCollections(criteria.list());
		
		return to;
	}
	
	public TransportObject findListByID(String id, int start, int size)
	{
		Criteria criteria = this.getSession().createCriteria(this.entityClass);
		criteria.add(Restrictions.eq("id", id));
		return findList(criteria, null, start, size);
	}

}
